import { onMounted, onUnmounted, ref } from "vue";
const scrollToEnd = function (selector?: string) {
  console.log("scrollToEnd函数加载");
  // 先决条件加个判断就好了，看一下函数守卫
  const isSrollToEnd = ref(false);
  let DOM: Element | Document | null = document;

  const handler = function (e) {
    console.log("handle", e);
    const isScrollBottom =
      e.target.scrollHeight <= e.target.scrollTop + e.target.clientHeight + 10;
    console.log(isScrollBottom);
    if (isScrollBottom) {
      isSrollToEnd.value = true;
      console.log("i achieve bottom", isSrollToEnd);
    } else {
      isSrollToEnd.value = false;
      console.log("i am up", isSrollToEnd);
    }
  };
  // 防抖函数
  function debounce(fn, time) {
    return function (...args) {
      const that = this;
      clearTimeout(fn.tid);
      fn.tid = setTimeout(function () {
        fn.apply(that, args);
      }, time);
    };
  }
  const debounceFunc = debounce(handler, 100);
  onMounted(() => {
    // 对于DOM的操作要在渲染完成后
    if (selector && selector !== "") {
      DOM = document.querySelector(selector)
        ? document.querySelector(selector)
        : document;
    }
    // console.log('mounted', DOM)
    (DOM as Element | Document).addEventListener("scroll", debounceFunc);
  });
  onUnmounted(() => {
    (DOM as Element | Document).removeEventListener("scroll", debounceFunc);
  });
  return isSrollToEnd;
};

export default scrollToEnd;
